package com.lm.common.core.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;

import java.time.LocalDateTime;

/**
 * 自定义填充公共字段
 *
 * @author lm
 * @date 2019/8/29 09:30
 */
public class DateMetaObjectHandler implements MetaObjectHandler {

    private final static String CREATE_TIME = "createTime";
    private final static String UPDATE_TIME = "updateTime";
    private final static String DELETE_FLAG = "deleteFlag";
    private final static String VERSIONS = "versions";

    private static final Integer NOT_DELETEFLAG_VALUE = 0;
    private static final Integer OPTIMISTIC_LOCK_INIT_VALUE = 0;

    /**
     * 插入填充，字段为空自动填充
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        Object createTime = this.getFieldValByName(CREATE_TIME, metaObject);
        Object updateTime = this.getFieldValByName(UPDATE_TIME, metaObject);

        Object deleteFlag = this.getFieldValByName(DELETE_FLAG, metaObject);
        Object versions = this.getFieldValByName(VERSIONS, metaObject);

        if (null == createTime) {
            this.setFieldValByName(CREATE_TIME, LocalDateTime.now(), metaObject);
        }

        if (null == deleteFlag) {
            this.setFieldValByName(DELETE_FLAG, NOT_DELETEFLAG_VALUE, metaObject);
        }

        if (null == versions) {
            this.setFieldValByName(VERSIONS, OPTIMISTIC_LOCK_INIT_VALUE, metaObject);
        }
    }

    /**
     * 更新填充
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName(UPDATE_TIME, LocalDateTime.now(), metaObject);
    }

}
